package com.mp.approvalreq.servlet.Attendance;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.*;
import com.mp.approvalreq.service.ApprovalDataServicePrx;
import com.mp.approvalreq.servlet.AbstractServlet;
import com.mp.checkin.util.DateTimeUtils;
import com.mp.user.entity.User;
import com.mp.user.service.UserServicePrx;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.util.DateTimeHelper;
import com.plusmoney.util.Utils;
import com.qq.tars.client.util.ServantUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 批量获得全公司某月请假的审批
 * 输入"{"contacts:[1,2,3,4],"date":"2016-10"}"
 *
 * @author Administrator
 */
@WebServlet("/glrcm")
public class GetLeaveRequestCurrentMonth extends AbstractServlet {

	private static final long serialVersionUID = -6524473373623928868L;

	private static final Logger logger = LoggerFactory.getLogger(GetLeaveRequestCurrentMonth.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			JSONObject jo = getJsonObject(req);

			String date = jo.getString("date");
			List<Integer> contactIds = JSONObject.parseArray(jo.getString("contacts"), Integer.class);

			UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
			List<User> userList = userServicePrx.getUserBaseInfoListByContactIds(contactIds);
			if (Utils.isEmpty(userList)) {
				throw new RpcServerLogicalException(1, "用户不存在");
			}
			// companyInfoId和contactId集合的映射关系
			Map<Integer, Integer> idMap = getIdMap(userList);
			// 查询参数
			ApprovalQuery query = getQuery(date, userList, idMap);
			ApprovalDataServicePrx approvalDataServicePrx = ServantUtils.getObject(ApprovalDataServicePrx.class);
			List<Leave> leaves = approvalDataServicePrx.getLeaves(query);

			List<Time> times = new ArrayList<>();
			for (Leave leave : leaves) {
				if (!idMap.containsKey(leave.getCompanyInfoId())) {
					continue;
				}
				Time time = new Time();
				time.setContactId(idMap.get(leave.getCompanyInfoId()));
				time.setLeaveType(leave.getLeaveType());
				time.setStartTime(leave.getRealStartTime().getTime());
				time.setEndTime(leave.getRealEndTime().getTime());
				times.add(time);
			}

			returnResult(resp, times);
		} catch (Throwable e) {
			onThrowable(req, resp, e);
		}
	}

	private Map<Integer, Integer> getIdMap(List<User> userList) {
		Map<Integer, Integer> map = new HashMap<>(userList.size());
		for (User user : userList) {
			map.put(user.getCompanyInfoId(), user.getContactId());
		}
		return map;
	}

	private ApprovalQuery getQuery(String date, List<User> userList, Map<Integer, Integer> idMap) {
		ApprovalQuery query = new ApprovalQuery();
		query.setCompanyId(userList.get(0).getCompanyId());
		query.setCompanyInfoIds(new ArrayList<>(idMap.keySet()));
		List<String> dateList = DateTimeUtils.getMonthDateList(DateTimeUtils.getMonthFromDate(date));
		query.setStart(DateTimeHelper.parse(dateList.get(0), DateTimeHelper.YEAR_MONTH_DAY_PATTERN));
		query.setEnd(DateTimeHelper.parse(dateList.get(dateList.size() - 1), DateTimeHelper.YEAR_MONTH_DAY_PATTERN));
		return query;
	}


	private void returnResult(HttpServletResponse resp, List<Time> times) throws IOException {
		JSONObject returnJson = new JSONObject();
		returnJson.put("result", "0");
		returnJson.put("res_info", "获得成功");
		returnJson.put("data", times);

		logger.info(returnJson.toJSONString());

		printJson(resp, returnJson.toJSONString());
	}

	private JSONObject getJsonObject(HttpServletRequest req) throws IOException {
		String reqBody = getContent(req);
		logger.info("json参数 {}", reqBody);

		JSONObject jo;
		try {
			jo = JSONObject.parseObject(reqBody);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RpcServerLogicalException(1, "审批内容提交失败，请稍候再试");
		}
		if (!jo.containsKey("date") || !jo.containsKey("contacts")) {
			throw new RpcServerLogicalException(1, "参数错误");
		}
		return jo;
	}


}
